import os
import keyboard
import time
import pyperclip
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import Signal, QObject


class MySignals(QObject):
    responseClipboard = Signal(str)


my_signal = MySignals()


class UI:
    def __init__(self):
        self.app = QApplication([])
        self.window = QUiLoader().load('main.ui')
        self.window.searchNow.clicked.connect(self.searchNow)
        # insert list
        self.checkLibraries()
        # hotkey
        keyboard.add_hotkey('ctrl+c', self.responseCtrlV)
        my_signal.responseClipboard.connect(self.processClipboard)

    def responseCtrlV(self):
        """ call back of keyboard """
        if self.window.responseCtrl.isChecked():
            print(True)
            time.sleep(0.2)
            text = pyperclip.paste()
            my_signal.responseClipboard.emit(text)

    def processClipboard(self, text):
        """call back of signal"""
        self.window.searchFor.setText(text)
        self.searchNow()

    def getQuery(self) -> str:
        """ return the searching text """
        return self.window.searchFor.text().strip()

    def checkLibraries(self):
        """ insert all tiku into the list """
        libraries = os.listdir('./题库/')
        for i in libraries:
            self.window.librarySelect.addItem(i)

    def searchNow(self):
        """ Callback button of searchNow """
        currentLib = self.window.librarySelect.currentText()
        with open(f'./题库/{currentLib}', 'r', encoding='utf-8') as f:
            text = f.read()
        searchText = self.getQuery()
        indexx = text.find(searchText)

        previousIndex = indexx - 20
        if previousIndex < 0:
            previousIndex = 0

        if indexx != -1:
            keyword = text[indexx:indexx + len(searchText)]
            before = text[previousIndex:indexx]
            after = text[indexx + len(searchText):indexx + 400]
            html = f'<font size="4">{before}</font>' \
                   f'<font color="red" size="4">{keyword}</font>' \
                   f'<font size="4">{after}</font>'
            self.window.outputArea.setHtml(html)
        else:
            self.window.outputArea.setHtml(f'<font color="red" size="5">无匹配</font>')

    def run(self):
        self.window.show()
        self.app.exec_()


if __name__ == '__main__':
    ui = UI()
    ui.run()
